<template>
    <div style="margin-left: 400px;margin-top: 200px;">
        <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">
            <el-form-item label="设备类型" prop="devicetype">
                <el-input v-model="ruleForm.devicetype" />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceNo">
                <el-input v-model="ruleForm.deviceNo" />
            </el-form-item>
            <el-form-item label="状态" prop="state">
                <el-radio-group v-model="ruleForm.state">
                    <el-radio :value="1">正常</el-radio>
                    <el-radio :value="2">电量低</el-radio>
                    <el-radio :value="3">异常离线</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">
                    确定
                </el-button>
                <el-button @click="resetForm(ruleFormRef)">取消</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { axiosHelpers } from '@/http/axiosHelpers'
import { useRouter, useRoute } from 'vue-router'
import http from "@/api/http";
const router = useRouter();
const route = useRoute();
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
    id: route.query.id,
    nursingUnitId: route.query.nursingUnitId,
    devicetype: '',
    deviceNo: '',
    state: ''
})

// Original values to compare during validation
const originalValues = ref({
    devicetype: '',
    deviceNo: '',
    state: ''
})

// Reset form data when loading new equipment
const resetFormData = () => {
    ruleForm.id = route.query.id,
        ruleForm.nursingUnitId = route.query.nursingUnitId,
        ruleForm.devicetype = ''
    ruleForm.deviceNo = ''
    ruleForm.state = ''
}

// Define fantian function before it's used in the watcher
const fantian = () => {
    // Reset form data before fetching new data
    resetFormData()

    http.get(`/api/EquipmentSomeThing/GetEquipmentById?id=${route.query.id}`)
        .then(res => {
            if (res && typeof res === 'object') {
                // Ensure we're not carrying over old data
                Object.assign(ruleForm, res.data)
                // Store original values for comparison
                originalValues.value = {
                    devicetype: res.data.devicetype,
                    deviceNo: res.data.deviceNo,
                    state: res.data.state
                }
                console.log("Data loaded successfully:", ruleForm)
            } else {
                ElMessage.error("获取设备数据失败")
                console.error("Failed to get equipment data:", res)
            }
        })
        .catch(error => {
            ElMessage.error("获取设备数据失败")
            console.error("Error retrieving equipment data:", error)
        })
}

// Watch for route changes to reload data when ID changes
watch(() => route.query.id, (newId, oldId) => {
    if (newId && newId !== oldId) {
        resetFormData()
        fantian()
    }
}, { immediate: true })

// Watch for state changes to trigger validation
watch(() => ruleForm.state, (newVal) => {
    // When state changes to 2, validate devicetype and deviceNo
    if (Number(newVal) === 2 && ruleForm.devicetype && ruleForm.deviceNo) {
        // Re-validate the form
        ruleFormRef.value?.validateField(['devicetype', 'deviceNo'])
    }
})

// Store existing equipment data
const existingEquipment = ref<Array<{ id: string | number, devicetype: string, deviceNo: string, state: number }>>([])

// Fetch existing equipment data when component mounts
const fetchExistingEquipment = async () => {
    try {
        const res = await http.get('/api/EquipmentSomeThing/ShowEquipment?nursingUnitId=' + (route.query.nursingUnitId || ''))
        if (res && res.data) {
            existingEquipment.value = res.data
        }
    } catch (error) {
        console.error('Failed to fetch equipment data:', error)
    }
}

// Check if device type and number combination is already in use
const checkDeviceDuplicate = (deviceType: string, deviceNo: string): boolean => {
    // Skip current item in check
    return existingEquipment.value.some(item => 
        item.id !== ruleForm.id && // Skip current item
        item.devicetype === deviceType && 
        item.deviceNo === deviceNo
    )
}

onMounted(() => {
    if (!route.query.id) {
        ElMessage.warning("未获取到设备ID，请重试")
        router.push("/EquipmentShow")
    }
    fetchExistingEquipment()
})

const rules = reactive<FormRules>({
    devicetype: [
        { required: true, message: '设备类型不能为空', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (Number(ruleForm.state) === 2 && value && ruleForm.deviceNo) {
                    if (checkDeviceDuplicate(value, ruleForm.deviceNo)) {
                        callback(new Error('当状态为电量低时，该设备类型和编号不能重复使用'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    deviceNo: [
        { required: true, message: '设备编号不能为空', trigger: 'blur' },
        {
            validator: (rule: any, value: string, callback: any) => {
                if (Number(ruleForm.state) === 2 && value && ruleForm.devicetype) {
                    if (checkDeviceDuplicate(ruleForm.devicetype, value)) {
                        callback(new Error('当状态为电量低时，该设备类型和编号不能重复使用'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    state: [
        { required: true, message: '状态不能为空', trigger: 'blur' },
        {
            validator: (rule: any, value: any, callback: any) => {
                if (Number(value) === 2 && ruleForm.devicetype && ruleForm.deviceNo) {
                    // Check if values have changed - only validate if they're different from original
                    const typeChanged = ruleForm.devicetype !== originalValues.value.devicetype
                    const noChanged = ruleForm.deviceNo !== originalValues.value.deviceNo
                    const stateChangedTo2 = Number(originalValues.value.state) !== 2 && Number(value) === 2
                    
                    if ((typeChanged || noChanged || stateChangedTo2) && 
                        checkDeviceDuplicate(ruleForm.devicetype, ruleForm.deviceNo)) {
                        callback(new Error('当状态为电量低时，该设备类型和编号不能重复使用'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            },
            trigger: 'change'
        }
    ],
})

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            http.post(`/api/EquipmentSomeThing/UpdateEquipment`, ruleForm)
                .then(res => {
                    ElMessage.success("修改成功")
                    router.replace("/EquipmentShow")
                })
                .catch(error => {
                    ElMessage.error("修改失败")
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    router.replace("/EquipmentShow")
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))
</script>
